package cn.com.callback

import cn.com.callback.ServiceBackInvoke
import cn.com.kh.KHDBConfig
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import cn.com.elite.EliteBean;
import cn.com.elite.Util
import org.json.JSONArray;
import org.json.JSONObject

import java.nio.charset.StandardCharsets
import java.nio.file.Files;
import java.nio.file.Paths;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.jdbc.core.JdbcTemplate;
import java.time.Instant;

import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.ArrayList;
import java.util.Properties;

import javax.mail.Session;
import javax.mail.Transport;

import org.apache.commons.mail.util.MimeMessageParser;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message.RecipientType;
import javax.mail.PasswordAuthentication;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.util.ByteArrayDataSource;
import org.apache.commons.io.FileUtils;
import javax.activation.DataSource;
import cn.com.kh.getProperty;
import cn.com.kh.KHUtil

import java.util.regex.Matcher
import java.util.regex.Pattern

/**
 *
 * @Title: apiHstSendEmailWorkorder* @Description: 定期扫描 邮件账号发送邮件任务 --内部接口
 * @author: chieh* @date 2023-11-16 下午15:30:48
 *
 */

public class apiHstSendEmailWorkorder implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(apiHstSendEmailWorkorder.class);
    private static SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {
        response.setCharacterEncoding("UTF-8");

        String getMethod = request.getMethod();

        log.debug("getMethod:" + getMethod);
        long endTime;
        String inData = "";
        String outData = "";
        String dataSourceID = "dataSource";

        BufferedReader iny = null;
        if (getMethod.equals("GET")) {
            inData = request.getParameter("data");
            log.debug("原始Get请求参数:" + inData);
        } else {
            InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
            iny = new BufferedReader(reader);
            String line;
            while ((line = iny.readLine()) != null) {
                inData += line;
            }
            log.debug("原始Post请求参数:" + inData);
        }

        String SYS_OUTDomain = KHDBConfig.getAPIURL(eliteBean, "SYS_OUTDomain");

        String ipserver = "smtp-mail.outlook.com";//邮箱服务器
        String sslport = "587";//SSL端口

        String urladdress = "";//邮箱地址
        String DOCUMENTOUT_GUID = "";//邮件GUID
        String documentpath = "";//邮件eml文件路径
        String access_token = "";//access_token

        //初始化 邮件附件图片的存储路径 检查
        SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd");
        String time = dateformat.format(System.currentTimeMillis());

        //源文件路径  /nfs/ngsfiles/richeditor
        String sourceFilePath = getProperty.get("EMAIL.sourceFilePath");
        //复制文件路径 /nfs/webchatfiles/richeditor
        String targetFolderPath = getProperty.get("EMAIL.targetFolderPath");
        //实际最终公网访问的图片url路径 https://callcenter.hszq8.com/webchat/download?file=
        String webchatrul = getProperty.get("EMAIL.webchatrul");

        //检查邮件富文本附件的路径下文件夹是否存在  每日生成的时间路径
        String FILEURLtime = targetFolderPath + "/" + time;
        //路径是否存在
        File filefolder = new File(FILEURLtime);
        //如果文件夹不存在则创建
        if (!filefolder.exists() && !filefolder.isDirectory()) {
            log.debug("//不存在");
            filefolder.mkdir();
        } else {
            log.debug("//目录存在");
        }

        //检查token有效期 是否需要重新刷新
        Map<String, String> headMap = new HashMap<String, String>();
        headMap.put("Content-Type", "application/json");
        //获取配置参数
        String sysurltoken = getProperty.get("crmurl");//配置本地接口地址
        sysurltoken = sysurltoken + "apiSync_refresh_token";
        //华盛证券，自动刷新Esop邮件token
        Util.doHttpPostUseHead(sysurltoken, "{}", "UTF-8", 100000, 0, headMap);

        //动态 获取华盛通邮箱地址 'hs.kf@hstong.com'
        String Fromel_Address= KHDBConfig.getParamConfig(eliteBean,"Fromel_Address");

        List selectconfigList = eliteBean.chaxun_sql("select h.urladdress,d.DOCUMENTOUT_GUID,d.documentpath,h.access_token from documentout d " +
                "left join staff s on d.handleby_id=s.STAFF_ID " +
                "left join hst_email_config h on 1=1 and (h.urladdress=d.DOCUMENTFROM or (h.sslport=d.DOCUMENTFROM and h.urladdress=case when d.hst_no is not null and d.hst_no<>'' then SUBSTRING(d.hst_no,LOCATE('/', d.hst_no)+1,length(d.hst_no)) else h.urladdress end)) " +
                "left join hst_email_parameter p on p.hst_guid=h.ipserver " +
                "where 1=1 and d.DOCTYPE=2  and  d.status=0 and d.TRIALCOUNTLIMIT>d.TRIALCOUNT and d.CREATEDDATE> DATE_SUB(CURDATE(),INTERVAL 7 DAY) " +
                "and d.DOCUMENTFROM <>'" + Fromel_Address + "' and h.status=1 " +
                "order by d.CREATEDDATE asc", "dataSource");
        def configcount = selectconfigList.size();
        log.debug("待处理的邮件配置数量 configcount：" + configcount);

        for (int i = 0; i < configcount; i++) {
            try {
                Map selectbrandMap = selectconfigList.get(i);
                urladdress = selectbrandMap.get("urladdress");
                DOCUMENTOUT_GUID = selectbrandMap.get("DOCUMENTOUT_GUID");
                documentpath = selectbrandMap.get("documentpath");
                access_token = selectbrandMap.get("access_token");

                log.debug("解析当前规则配置：urladdress:" + urladdress + "	DOCUMENTOUT_GUID:" + DOCUMENTOUT_GUID + "	documentpath:" + documentpath + "	access_token:" + access_token);

                String SENDPATH = getProperty.get("EMAILSENDPATH");//eml存储附件的路径 /nfs/ngsfiles
                log.debug("文件夹SENDPATH:" + SENDPATH);
                // documentpath = /email/2023_11_16/bcc4faf3-be65-48bf-b8c0-339cd79be823_1700098023371.eml
                String SENDPATHEML = SENDPATH + documentpath;//eml文件 全路径
                log.debug("eml全路径SENDPATHEML:" + SENDPATHEML);
                //https://callcenter.hszq8.com/webchat/download?file=ngsfiles/hst/个人话术导入模板.xlsx
                //http://47.113.26.123:8080/ngs/fs/get?file=

                String encodedString = Base64.getEncoder().encodeToString(readAsString5(SENDPATHEML).replaceAll("\"/ngs/fs/get\\?file=3D", "\""+SYS_OUTDomain + "/webchat/download\\?file=3Dngsfiles/").getBytes());
                System.out.println("Encoded String: " + encodedString);

                //微软邮件api 模式发送
                log.debug("-------------------------start 微软邮件api 模式发送开始调用 -----------------");

                headMap.put("Content-Type", "text/plain");
                headMap.put("Authorization", "Bearer " + access_token);
                //log.debug("调度微软邮箱api参数sendmailObject:" + sendmailObject.toString());
                //获取配置参数
                String sysurl = "https://graph.microsoft.com/v1.0/me/sendMail";
                Util.doHttpPostUseHead(sysurl, encodedString, "UTF-8", 100000, 0, headMap);

                //更新发送标记 成功
                eliteBean.update("update documentout set STATUS=1,TRIALCOUNT=TRIALCOUNT+1,MODIFIEDDATE=NOW(),MODIFIEDBY='SELITE',LASTTRYDATETIME=now() where DOCUMENTOUT_GUID='" + DOCUMENTOUT_GUID + "' ", "dataSource");
            } catch (Exception e) {
                eliteBean.update("update documentout set STATUS=5,TRIALCOUNT=TRIALCOUNT+1,MODIFIEDDATE=NOW(),MODIFIEDBY='SELITE' where DOCUMENTOUT_GUID='" + DOCUMENTOUT_GUID + "' ", "dataSource");
                log.error(urladdress + " 当前邮件处理异常:" + e.getMessage());
            }
        }

        outData = "{\"resultcode\":\"1\",\"resultmessage\":\"处理成功\",\"data\":[]}";
        log.debug("返回结果:" + outData);
        return outData;
    }

    public static String readAsString5(String path) {
        try {
            Scanner scanner = new Scanner(Paths.get(path), StandardCharsets.UTF_8.name());
            String content = scanner.useDelimiter("\\A").next();
            scanner.close();
            return content;
        } catch (Exception exception) {
            return null;
        }
    }

    // 解析Json值
    public static String GetJV(JSONObject inJson, String getKey) {
        String Rev_Value = null;
        try {
            Rev_Value = inJson.getString(getKey);
        } catch (Exception e) {
            try {
                Rev_Value = String.valueOf(inJson.getInt(getKey));
            } catch (Exception e1) {
                try {
                    Rev_Value = String.valueOf(inJson.getJSONArray(getKey));
                } catch (Exception e2) {
                    try {
                        Rev_Value = String.valueOf(inJson.getJSONObject(getKey));
                    } catch (Exception e3) {
                        Rev_Value = "";
                    }
                }
            }
        } finally {
            if (Rev_Value == null || Rev_Value.equals("null") || Rev_Value.length() <= 0) {
                Rev_Value = "";
            } else {
            }
        }
        //log.debug("解析-k=" + getKey + " v=" + Rev_Value);
        return Rev_Value;
    }


}
